package master;

import master.Employer;
import master.EmployerTableModel;
import master.EmployerService;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.util.List;

public class ManagerFrm extends JFrame {
    private JTable employerTable;
    private JScrollPane scrollPane;
    private EmployerService employerService;
    private EmployerTableModel tableModel;
    public ManagerFrm(Employer loggedInUser) {
        // 初始化服务
        employerService = new EmployerService();

        // 设置窗口
        setTitle("管理员界面-"+loggedInUser.getEname());
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(800, 600);
        setLocationRelativeTo(null);

        initUI();
        loadEmployerData();

//        JPanel topPanel = new JPanel();
//        add(topPanel, BorderLayout.NORTH);

        // 中间内容区域
//        JLabel contentLabel = new JLabel("系统主界面", JLabel.CENTER);
//        contentLabel.setFont(new Font("微软雅黑", Font.PLAIN, 24));
//        add(contentLabel, BorderLayout.CENTER);

        // 如果是管理员，显示管理员按钮
//        if (employee.getRole() == 2) {
//            JButton manageButton = new JButton("员工管理");
//            topPanel.add(manageButton);
//        }
    }

    private void initUI() {
        // 主板面
        JPanel mainPanel = new JPanel(new BorderLayout());

        // 标题
        JLabel titleLabel = new JLabel("信息管理", JLabel.CENTER);
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 24));
        mainPanel.add(titleLabel, BorderLayout.NORTH);

        // 中间——表格
//        employerTable = new JTable();
//        scrollPane = new JScrollPane(employerTable);
//        mainPanel.add(scrollPane, BorderLayout.CENTER);
        // 信息表格
        tableModel = new EmployerTableModel();
        employerTable = new JTable(tableModel);
        mainPanel.add(new JScrollPane(employerTable), BorderLayout.CENTER);

        // 底部按钮面板
        JPanel buttonPanel = new JPanel();

        JButton refreshButton = new JButton("刷新");
        refreshButton.addActionListener(e->loadEmployerData());

        JButton addButton = new JButton("添加");
        addButton.addActionListener(e->showAdd());

        JButton editButton = new JButton("编辑");
        addButton.addActionListener(e->showEdit());

        JButton deleteButton = new JButton("删除");
        deleteButton.addActionListener(e->delete());

        JButton logoutButton = new JButton("退出");
        logoutButton.addActionListener(e->{
            dispose();
//            new LoginFrm().setVisible(true);
        });

        //把按钮加入按钮面板
        buttonPanel.add(refreshButton);
        buttonPanel.add(addButton);
        buttonPanel.add(editButton);
        buttonPanel.add(deleteButton);
        buttonPanel.add(logoutButton);

        // 添加按钮面板到主面板
        mainPanel.add(buttonPanel, BorderLayout.SOUTH);

        add(mainPanel);

    }

    private void loadEmployerData() {
        // 从服务层获取所有数据
        List<Employer> employers = employerService.getAllEmployers();

        // 表头
        String[] columnNames = {"编号", "姓名", "岗位", "部门编码", "登录密码", "角色"};

        // 表格数据
        Object[][] data = new Object[employers.size()][6];
        for (int i = 0; i < employers.size(); i++) {
            Employer employer = employers.get(i);
            data[i][0] = employer.getEmpno();
            data[i][1] = employer.getEname();
            data[i][2] = employer.getJob();
            data[i][3] = employer.getDeptno();
            data[i][4] = employer.getPassword();
            data[i][5] = employer.getRole() == 2 ? "管理员" : "员工";
        }

        // 设置表格模型
        DefaultTableModel model = new DefaultTableModel(data, columnNames) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            } // 所有单元格不可编辑
        };

        employerTable.setModel(model);
    }

    private void showAdd() {
        JDialog dialog = new JDialog(this, "添加", true);
        dialog.setBounds(400, 250, 500, 400);
        dialog.setLayout(new GridLayout(7, 2, 10, 10));

        // 表单字段
        JTextField empnoField = new JTextField();
        JTextField enameField = new JTextField();
        JTextField jobField = new JTextField();
        JTextField deptnoField = new JTextField();
        JPasswordField passwordField = new JPasswordField();
        JComboBox<String> roleCombo = new JComboBox<>(new String[]{"员工", "管理员"});

        // 添加组件
        dialog.add(new JLabel("员工编号"));
        dialog.add(empnoField);
        dialog.add(new JLabel("姓名："));
        dialog.add(enameField);
        dialog.add(new JLabel("岗位："));
        dialog.add(jobField);
        dialog.add(new JLabel("部门编号："));
        dialog.add(deptnoField);
        dialog.add(new JLabel("密码："));
        dialog.add(passwordField);
        dialog.add(new JLabel("角色："));
        dialog.add(roleCombo);

        // 按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 10));
        JButton saveButton = new JButton("保存");
        saveButton.addActionListener(e->{
            // 获取并验证数据
            int empno = Integer.parseInt(empnoField.getText().trim());
            String ename = enameField.getText().trim();
            String job = jobField.getText().trim();
            int deptno = Integer.parseInt(deptnoField.getText().trim());
            String password = new String(passwordField.getPassword());
            int role = roleCombo.getSelectedIndex()+1;

            Employer newEmployer = new Employer();
            newEmployer.setEmpno(empno);
            newEmployer.setEname(ename);
            newEmployer.setJob(job);
            newEmployer.setDeptno(deptno);
            newEmployer.setPassword(password);
            newEmployer.setRole(role);

            boolean success = employerService.addEmployer(newEmployer);
            if (success) {
                JOptionPane.showMessageDialog(dialog, "添加成功");
                dialog.dispose();
                loadEmployerData();
            } else {
                JOptionPane.showMessageDialog(dialog, "添加失败");
            }
        });
        buttonPanel.add(saveButton);

        JButton cancelButton = new JButton("取消");
        cancelButton.addActionListener(e->dialog.dispose());
        buttonPanel.add(cancelButton);

        dialog.add(new JLabel()); // 占位
        dialog.add(buttonPanel);

        dialog.setVisible(true);
    }

    private void showEdit() {
        int selectenRow = employerTable.getSelectedRow();
        if (selectenRow == -1) {
            JOptionPane.showMessageDialog(this, "请先选择要编辑的员工");
            return;
        }

        int empno = (int) employerTable.getValueAt(selectenRow, 0);
        JOptionPane.showMessageDialog(this, "准备编辑员工编号"+empno);
    }

    private void delete() {
        int selectedRow = employerTable.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "请先选择要删除的员工");
            return;
        }

        int empno = (int) employerTable.getValueAt(selectedRow, 0);
        String ename = (String) employerTable.getValueAt(selectedRow, 1);

        int confirm = JOptionPane.showConfirmDialog(
                this,
                "确定要删除"+ename+"（编号："+empno+"）吗？",
                "确认删除",
                JOptionPane.YES_NO_OPTION
        );

        if (confirm == JOptionPane.YES_NO_OPTION) {
            JOptionPane.showMessageDialog(this, "删除成功");
            loadEmployerData();
        }
    }

    public static void main(String[] args) {
//        Employer employer = new Employer();
//        EventQueue.invokeLater(()->{
//            ManagerFrm frm = new ManagerFrm(employer);
//            frm.setVisible(true);
//        });
        SwingUtilities.invokeLater(()->{
            Employer testUser = new Employer();
            ManagerFrm frm = new ManagerFrm(testUser);
            frm.setVisible(true);
        });
    }
}
